package com.situ.company.employee.service;

import java.util.List;

import com.situ.company.employee.dao.EmployeeDao;
import com.situ.company.employee.model.EmployeeModel;
import com.situ.company.util.MD5;
import com.situ.company.util.UpLoad;

public class EmployeeService {
    
    private EmployeeDao dao = new EmployeeDao();
    private String pass = MD5.encode("123");

    /**
     * <p>Description: </p>  
     * @param model
     * @return 1=注册成功/ null=后台异常，数据没插入数据库 / repeat账号重复
     */
    public String insert(EmployeeModel model) {
        EmployeeModel m0 = new EmployeeModel(model.getCode());
        if(model.getPass() == null)
            model.setPass(pass);
        EmployeeModel mdb = dao.selectModel(m0);
        if(mdb == null) {
            model.setPass(MD5.encode(model.getPass()));
            Integer res = dao.insert(model);
            return res == null ? null:res.toString();
        }else {
            return "repeat";
        }
    }
    
    public String delete(EmployeeModel model) {
        return dao.delete(model) + "";
    }

    public String update(EmployeeModel model) {
//        if(model.getPass() != null) {
//            model.setPass(MD5.encode(model.getPass()));
//        }
        return dao.updateActive(model) + "";
    }

    public List<EmployeeModel> selectList(EmployeeModel model) {
        String code = model.getCode();
        model.setCode(code == null ? "%%" : "%" + code + "%");
        String name = model.getName();
        model.setName(name == null ? "%%" : "%" + name + "%");
        return dao.selectList(model);
    }

    public EmployeeModel selectModel(EmployeeModel model) {
        EmployeeModel m0 = new EmployeeModel(model.getCode());
        return dao.selectModel(m0);
    }

    /**
     * <p>Description: 0=账号不存在，1登录成功， 2密码错误</p>  
     * @param model
     * @return
     */
    public String login(EmployeeModel model) {
        EmployeeModel m0 = selectModel(model);
        if(m0 == null)
            return "0";
        String pass = model.getPass();
        pass = MD5.encode(pass);
        return m0.getPass().equals(pass) ? "1":"2";
    }

    public Integer selectCount(EmployeeModel model) {
        EmployeeModel m0 = new EmployeeModel();
        String code = model.getCode();
        m0.setCode(code == null ? "%%" : "%" + code + "%");
        String name = model.getName();
        m0.setName(name == null ? "%%" : "%" + name + "%");
        return dao.selectCount(m0);
    }

    public String resetPass(EmployeeModel model) {
        EmployeeModel m0 = new EmployeeModel(model.getCode(), pass);
        return dao.updateActive(m0) + "";
    }

    public String delPic(EmployeeModel model) {
        EmployeeModel mdb = selectModel(model);
        String image = mdb.getImage();
        UpLoad.delFile(image);
        model.setImage("");
        return dao.updateActive(model) + "";        
    }


}
